﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace RemoteObject
{
    public class UploadRequestor
    {
        private string remoteFile;
        private string localFile;
        private RemoteObject.MyRemoteObject robj;
        private float progress;
        private float downloadSpeed;
        private Common.Status jobStatus;
        private long jobID;
        private String sourceHost;

        public UploadRequestor(string fnRemote, string fnLocal)
        {
            remoteFile = fnRemote;
            localFile = fnLocal;
            robj = (RemoteObject.MyRemoteObject)Activator.GetObject(typeof(RemoteObject.MyRemoteObject), Common.CloudServerURL);
            progress = 0;
            downloadSpeed = 0;
            jobStatus = Common.Status.Pause;
            jobID = robj.GetNewClientID();
            sourceHost = Common.LocalIPAddress;
        }

        public UploadRequestor(string fnRemote, string fnLocal, string fromSourceHost)
            : this(fnRemote, fnLocal)
        {
            sourceHost = fromSourceHost;
        }

        public void StartUpload()
        {
            if (jobStatus == Common.Status.Working || jobStatus == Common.Status.Completed) return;
            jobStatus = Common.Status.Working;
            robj.StartUploadRequest(remoteFile, localFile, Common.LocalIPAddress, jobID);
            Thread SyncThread = new Thread(new ThreadStart(this.Sync));
            SyncThread.Start();
        }

        public void StopUpload()
        {
            robj.StopUploadRequest(jobID);
            jobStatus = Common.Status.Pause;
        }

        public void RestartUpload()
        {
            StopUpload();
            Thread.Sleep(1000);
            StartUpload();
        }

        public String GetJobName()
        {
            return localFile.Substring(localFile.LastIndexOf("\\") + 1);
        }

        public void Sync()
        {
            do
            {
                RemoteObject.JobInfo jobinfo = robj.SyncRequest(jobID);
                progress = jobinfo.progress;
                downloadSpeed = jobinfo.downloadSpeed;
                if (progress == 100)
                {
                    jobStatus = Common.Status.Completed;
                    Thread.CurrentThread.Abort();
                }
                Thread.Sleep(1000);
            } while (true);
        }

        public float GetProgress()
        {
            return progress;
        }

        public float GetDownloadSpeed()
        {
            return downloadSpeed;
        }

        public Common.Status GetStatus()
        {
            return jobStatus;
        }

    }
}
